var param = null;
var rows = null;
var searchParam = {subject:"", state: ""};
$(function(){
	jQuery("#gridTable1").jqGrid({
		url: basePath + '/server/ajax.do',
		datatype: 'json',
		height: 250,
		autowidth: true,
	   	colNames:['新闻标题', '状态', '添加时间'],
	   	colModel:[
	   		{name:'subject',index:'subject', width:140},
	   		{name:'state',index:'state', width:60, align:"center", formatter: function(cellvalue, options, rowObject) {
				if(cellvalue == "1"){
					return "正常";
				} else {
					return "屏蔽";
				}
			}},
	   		{name:'add_time',index:'add_time', width:80, align:"left"}	
	   	],
	   	beforeRequest:function(){//向服务器端发起请求之前触发此事件但如果datatype是一个function时例外
        	param = $("#gridTable1").jqGrid("setGridParam")[0].p;
        	rows = null;
			$("#gridTable1").jqGrid("setGridParam", { //设置查询参数
				postData:{
					"iFunc": AjaxUtil.command.FUNC_PAGING,
					"strData": $.toJSON({
						sqlID: "sjc_news_manage_1",
						parameters: {sortname:param.sortname, sortorder:param.sortorder,
							subject: searchParam.subject,
							state: searchParam.state
						},
						offset: (param.page-1)*param.rowNum,
						maxsize: param.rowNum
					})
				}
			});
		},
		jsonReader: {
			root: "query",			// 数据行（默认为：rows）
            page: function (obj) { // 当前页
            		rows = obj.query;
            		return param.page;
            	},
            total: function (obj) { return Math.ceil(obj.total/param.rowNum); },			// 总页数
            records: "total",		// 总记录数
            repeatitems: false,
			id: "news_id"
		},
	   	multiselect: true,
	   	sortname: 'add_time',
	    sortorder: "desc",
	   	rowNum:10,
	   	rowList:[10,20,30],
	   	pager: '#gridPager1',
	   	caption: "新闻管理"
	});
	jQuery("#gridTable1").jqGrid("navGrid", "#gridPager1", {
		search : false,
        addfunc : openAdd,
        editfunc : openEdit,
        delfunc : openDel,
        alerttext : "请选择需要操作的数据行!"  // 当未选中任何行而点击编辑、删除、查看按钮时，弹出的提示信息  
    }).jqGrid('navButtonAdd',"#gridPager1",{
    	caption : '',
    	title : '查找',
    	position : 'first',
    	buttonicon : 'ui-icon-search',
    	onClickButton : openSearch
    });
    
    //设置弹出查询窗口参数
	$("#searchform").dialog({
        height:180,
        width:380,
        resizable:false,
        modal:true,  //这里就是控制弹出为模态
        buttons:{
            "取消":function(){$(this).dialog("close");},
            "重置":function(){
            	$("#searchform input").each(function(){
					$(this).val("");
				});
				$("#key_state").val("");
            },
            "查询":function(){
            	searchParam.subject = $("#key_subject").val();
            	searchParam.state = $("#key_state").val();
            	$(this).dialog("close");
            	$("#gridTable1").jqGrid('setCaption', getTitle()).jqGrid('setGridParam').trigger("reloadGrid", [ {page: 1} ]);
            }
        }
    }).dialog("close");
    
    //设置弹出编辑窗口参数
	$("#modifyform").dialog({
        height:450,
        width:720,
        resizable:false,
        modal:true,  //这里就是控制弹出为模态
        buttons:{
            "取消":function(){$(this).dialog("close");},
            "确定":function(){
            	var arrSql = [];
            	if($("#news_id").val() == "") {
            		arrSql.push({
        				sqlID: 'sjc_news_manage_2',
        				parameters: {
        					subject: $("#subject").val(),
        					content: ewHTML(),
        					state: $("#state").val()
        				}
        			});
            	} else {
            		arrSql.push({
        				sqlID: 'sjc_news_manage_3',
        				parameters: {
        					news_id: $("#news_id").val(),
        					subject: $("#subject").val(),
        					content: ewHTML(),
        					state: $("#state").val()
        				}
        			});
            	}
        		
        		if(AjaxUtil.command.isSucceed(AjaxUtil.command.executeTransaction(arrSql))) {
    				$("#modifyform").dialog("close");
    				if($("#news_id").val() == "") {
    					$("#gridTable1").jqGrid('setGridParam').trigger("reloadGrid", [ {page: 1} ]);
    				} else {
    					$("#gridTable1").jqGrid('setGridParam').trigger("reloadGrid");
    				}
    				$.jqalert("保存成功！");
    			} else {
    				$.jqalert("保存失败！");
    			}
            }
        }
    }).dialog("close");
    
	$("#gridTable1").jqGrid('setCaption', getTitle())
})

function openSearch() {
	$("#searchform").dialog("open");
}

function openAdd() {
	$("#modifyform input").each(function(){
		$(this).val("");
	});
	$("#state").val("1");
	
	$("#modifyform").dialog("open");
	$("#modifyform").dialog("option", 'title', '添加');
	ewHTML("");
}

function openEdit() {
	var selectedIds = $("#gridTable1").jqGrid("getGridParam", "selarrrow");
	if(selectedIds.length != 1) {
		$.jqalert("请选择一条要编辑的记录");
		return;
	}
	var data = getRow(selectedIds[0]);
	if(data == null) {
		$.jqalert("请选择一条要编辑的记录");
		return;
	}
	
	$("#news_id").val(data.news_id);
	$("#subject").val(data.subject);
	$("#state").val(data.state);
	
	$("#modifyform").dialog("open");
	$("#modifyform").dialog("option", 'title', '编辑');
	ewHTML(data.content);
}

function openDel() {
	var selectedIds = $("#gridTable1").jqGrid("getGridParam", "selarrrow");
	$.jqconfirm("确定删除选中的记录吗?", "确认提示", function() {
		var arrSql = [];
		for(var i=0; i<selectedIds.length; i++) {
			 arrSql.push({
			 	sqlID: 'sjc_news_manage_4',
        		parameters: {
        			news_id: selectedIds[i]
       			}
       		});
		}
		if(AjaxUtil.command.isSucceed(AjaxUtil.command.executeTransaction(arrSql))){
			$("#gridTable1").jqGrid('setGridParam').trigger("reloadGrid");
			$.jqalert("删除成功！");
		} else {
			$.jqalert("删除失败！");
		}
	});
}

function getRow(id) {
	if(rows == null) return null;
	for(var i=0; i<rows.length; i++) {
		if(rows[i].news_id == id) return rows[i];
	}
	return null;
}

function ewHTML(val) {
	var o_Editor = document.getElementById("eWebEditor1").contentWindow;
	if(val === undefined) {
		return o_Editor.getHTML();
	} else {
		o_Editor.setHTML(val);
	}
}

function getTitle() {
	var s = "新闻管理 【";
	if(searchParam.subject != "") s += searchParam.subject + "&nbsp;&nbsp;";
	else s += "所有&nbsp;&nbsp;";
	s += $("#key_state").find("option:selected").text();
	s += "】";
	return s;
}
